<?php
class ProductController extends Apps_Controller_Action_Default {

    public function categoryAction() {
        $id = intval($this->_request->getParam('id'));

        if(!$id) {
            $this->_redirect('home');
        }

        $tbCategory = new Model_DbTable_ProductCategory();
        $category = $tbCategory->fetchRow(array('id =?' => $id, 'status =?' => $tbCategory::STATUS_ACTIVE), array('ASC' => 'sorting_number'));
        if(!$category) {
            $this->_redirect('home');
        }

        $tbProduct = new Model_DbTable_Product();
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();

        $products = array();

        if($category['parent_id'] == 0) {
            $childCategorys = $tbCategory->fetchAll(array('parent_id =?' => $id, 'status =?' => $tbCategory::STATUS_ACTIVE), array('ASC' => 'sorting_number'));

            if($childCategorys->count()) {
                foreach ($childCategorys as $childCategory) {
                    $products[$childCategory['title']] = $tbProduct->listByCategoryId($childCategory['id']);
                }
            }else {
                $products[$category['title']] = null;
            }

        } else {
            $products[$category['title']] = $tbProduct->listByCategoryId($id);
        }

        $this->view->products = $products;
        $this->view->category = $category;

        //meta tag
        $tbSiteSetting = new Model_DbTable_SiteSetting();
        $setting   = $tbSiteSetting->getMetaTag();
        $this->_page_meta_keywords    = $category['meta_keyword'] ? $category['meta_keyword'] : ($setting['meta_keyword'] ? $setting['meta_keyword'] : $this->_default_keyword);
        $this->_page_meta_description = $category['meta_description'] ? $category['meta_description'] : ($setting['meta_description'] ? $setting['meta_description'] : $this->_default_description);
        $this->_page_title 	  		  = $category['header_title'] ? $category['header_title'] : ($setting['header_title'] ? $setting['header_title'] : $this->_default_header_title);
    }


    public function detailAction() {
        $id = intval($this->_request->getParam('id'));

        if(!$id) {
            $this->_redirect('/home');
        }

        $tbProduct = new Model_DbTable_Product();
        $product = $tbProduct->getById($id);

        if(!$product) {
            $this->_redirect('/home');
        }


        $tbProductImage = new Model_DbTable_ProductImage();
        $productImages  = $tbProductImage->listByProductId($id);


        $tbProductColor = new Model_DbTable_ProductColor();
        $productColors  = $tbProductColor->listByProductColorJson($product['color']);

        $tbProductSize = new Model_DbTable_ProductSize();
        $productSizes  = $tbProductSize->listByProductSizeJson($product['size']);

        $productOther = $tbProduct->listOther($id, $product['product_category_id']);

        $this->view->product       = $product;
        $this->view->productOther  = $productOther;
        $this->view->productImages = $productImages;
        $this->view->productColors = $productColors;
        $this->view->productSizes  = $productSizes;


        //meta tag
        $tbSiteSetting = new Model_DbTable_SiteSetting();
        $setting   = $tbSiteSetting->getMetaTag();

        if(!$product['meta_keyword']) {
            $category = $this->getMetaCategoryById($product['product_category_id']);

            if($category['parent_id'] != 0 && !$category['meta_keyword']) {
                $category = $this->getMetaCategoryById($category['parent_id']);
            }

            $product['meta_keyword']     = $category['meta_keyword'];
            $product['meta_description'] = $category['meta_description'];
            $product['header_title']     = $category['header_title'];
        }

        $this->_page_meta_keywords    = $product['meta_keyword'] ? $product['meta_keyword'] : ($setting['meta_keyword'] ? $setting['meta_keyword'] : $this->_default_keyword);
        $this->_page_meta_description = $product['meta_description'] ? $product['meta_description'] : ($setting['meta_description'] ? $setting['meta_description'] : $this->_default_description);
        $this->_page_title 	  		  = $product['header_title'] ? $product['header_title'] : ($setting['header_title'] ? $setting['header_title'] : $this->_default_header_title);

        // ORDER FORM
        $f = new Form_Order();
        $f->getElement('id')->setValue($id);

        $this->view->form = $f;
    }

    public function createOrderAction() {
        $this->_helper->layout()->disableLayout();
        $rq = $this->_request;

        $message = 'Cảm ơn quý khách đã liên hệ đặt hàng với ohnew!';

        $f = new Form_Order();
        if($rq->isPost()) {
            if($f->isValid($rq->getParams())) {
                $pId = $f->getValue('id');

                $validator = new Zend_Validate_Db_NoRecordExists(array('table' => 'product', 'field' => 'id'));
                if($validator->isValid($pId)) {
                    // Error
                    $message = 'Gửi đơn hàng không thành công!';
                } else {
                    $fullName = $f->getValue('full_name');
                    $email = $f->getValue('email');
                    $phone = $f->getValue('phone');
                    $address = $f->getValue('address');
                    $message = $f->getValue('message');

                    $tbCustomer = new Model_DbTable_Customer();
                    $customer = $tbCustomer->fetchRow(array('email =?' => $email, 'phone =?' => $phone));

                    if($customer) {
                        $customerId = $customer['id'];
                    } else {
                        $customerId = $tbCustomer->safelyInsert(array(
                                    'full_name' => $fullName,
                                    'email' => $email,
                                    'phone' => $phone,
                                    'address' => $address,
                                    'status' => Model_DbTable_Customer::STATUS_INACTIVE
                                ));
                    }

                    $tbOrder = new Model_DbTable_Order();
                    $oId = $tbOrder->safelyInsert(array(
                                'customer_id' => $customerId,
                                'product_id' => $pId,
                                'message' => $message,
                                'status' => Model_DbTable_Order::STATUS_INACTIVE
                            ));

                    if($oId) {
                        $message = 'Cảm ơn quý khách đã liên hệ đặt hàng với ohnew! Nhân viên bán hàng của chúng tôi sẽ liên hệ lại với quý khách trong thời gian sớm nhất.';
                    } else {
                        $message = 'Gửi yêu cầu mua hàng không thành công, vui lòng liên hệ lại sau! Cảm ơn quý khách hàng.';
                    }
                }
            } else {
                $message = 'invalid';
            }
        }
        echo $message;
        //die;
    }


    public function newAction() {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $select = $dbAdapter
                      ->select()
                      ->from('product', null)
                      ->where('status =? ', Model_DbTable_Product::STATUS_ACTIVE)
                      ->where('is_new =? ', Model_DbTable_Product::STATUS_ACTIVE)
                      ->columns(array(
                                  'id' => 'product.id',
                                  'name' => 'product.name',
                                  'code' => 'product.code',
                                  'price_sale' => 'product.price_sale',
                                  'thumbnail_link' => 'product.thumbnail_link'
                              ));

        $products = $select->query()->fetchAll();

        $this->view->products = $products;
    }

    public function saleOffAction() {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $select = $dbAdapter
                      ->select()
                      ->from('product', null)
                      ->where('status =? ', Model_DbTable_Product::STATUS_ACTIVE)
                      ->where('is_sale_off =? ', Model_DbTable_Product::STATUS_ACTIVE)
                      ->columns(array(
                                  'id' => 'product.id',
                                  'name' => 'product.name',
                                  'code' => 'product.code',
                                  'price_sale' => 'product.price_sale',
                                  'thumbnail_link' => 'product.thumbnail_link'
                              ));

        $products = $select->query()->fetchAll();

        $this->view->products = $products;
    }

    public function getMetaCategoryById($categoryId) {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $select = $dbAdapter
                      ->select()
                      ->from('product_category', null)
                      ->where('id =? ', $categoryId)
                      ->columns(array(
                                  'id'                 => 'product_category.id',
                                  'parent_id'          => 'product_category.parent_id',
                                  'meta_keyword'       => 'product_category.meta_keyword',
                                  'meta_description'   => 'product_category.meta_description',
                  				  'header_title'	   => 'product_category.header_title',
                              ));

        return $select->query()->fetch();
    }
}